package public

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"fmt"
	"strconv"
	"strings"
	"time"
)

//文件保存的token

func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS7UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

//解析加密体，拿到时间
func DecodeAddrAndTime(pwd []byte) (addr string, now int) {
	s := string(pwd)
	list := strings.Split(s, "+")
	if len(list) < 2 {
		return "", 0
	}
	addr = list[0]
	now, err := strconv.Atoi(list[1])
	if err != nil {
		return "", 0
	}
	return addr, now

}

//AES加密
func AesEncrypt(origData, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	origData = PKCS7Padding(origData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

//AES解密
func AesDecrypt(crypted, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS7UnPadding(origData)
	return origData, nil
}

//获取token
func GetToken(addr string, csrf string) (string, error) {

	//添加时间参数
	nowTime := time.Now().Unix()
	addr = fmt.Sprintf("%s+%d", addr, nowTime)

	AesKey := []byte(csrf) //获取令牌
	enc, err := AesEncrypt([]byte(addr), AesKey)
	if err != nil {
		return "", err
	}

	token := base64.StdEncoding.EncodeToString(enc) //b64编码

	return token, nil

}

//测试token是否正确
//nil代表token正确
func DetectionToken(token string, csrf string) error {
	enc, err := base64.StdEncoding.DecodeString(token)
	if err != nil { //解码失败
		return NewError(TokenErr, 0, token)
	}
	AesKey := []byte(csrf) //获取令牌

	pwdByte, err := AesDecrypt(enc, AesKey)
	if err != nil {
		return NewError(TokenErr, 0, token)
	}

	addr, old := DecodeAddrAndTime(pwdByte)

	if addr == "" && old == 0 {
		return NewError(TokenErr, 0, token)
	}

	//过期
	if !(old+120 > int(time.Now().Unix())) {
		return NewError(TokenExpiredErr, 0, token)
	}

	return nil

}

//随机字符串密码
func RandomPwd() (s string) {
	var bas = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

	var t = int(time.Now().UnixNano())

	for i := 0; i < 16; i++ {
		s += string(bas[t%len(bas)])
		t /= 2
	}
	return s
}
